package com.bbcare.followup.plat.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientMergeService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientSwitchService;


/**
 * 用户基本信息队列，复制，建档
 */
@Controller
@RequestMapping("/service/patientSwitch")
public class PatientSwitchController {
    private final static Logger logger = Logger.getLogger(PatientSwitchController.class);

    @Autowired
    private IPatientSwitchService patientSwitchService;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private IFollowQueueService followQueueSerivce;
    @Autowired
    private IPatientMergeService mergeService;

    @Autowired
    private IPatientTaskContentDAO taskContentDAO;

    @Autowired
    private IPatientTaskDAO patientTaskDao;


    /**
     * 用户队列复制（关联）。
     * @param request
     * @param arg {followQueueId，}
     * @return
     * @throws Exception
     */
    @RequestMapping("/copyPatient")
    @ResponseBody
    public ResultModel<Map<String, Object>> copyPatient(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.warn("in copyPatient----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        // 参数校验后续补充
        final String queueId = jsonData.getString("followQueueId");
        jsonData.put("opNote","复制建档");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> chkMapIn = new HashMap<String, Object>();
        boolean isVerify = true;
        map.put("id", queueId);
        chkMapIn.put("queueId", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        if (null == queue) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
        }
        String queueUserType = queue.getQueueUsertype();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名

        //需要从新获取
        String tenantId = queue.getTenantId();
        String deptId = queue.getDeptId();
        if (StringUtils.isBlank(deptId)) {
            deptId = queue.getDeptId();
        }
        String opCode = "1000";
        String opType = "2";
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
        }
        if (StringUtils.isBlank(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
        }

        Map<String, Object> servParamMap = jsonData;
        String userType ="1";
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲），暂时写死，回头完善
            userType = "2";
            servParamMap.put("userType", userType);
        } else if (StringUtils.isBlank(userType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
        }
        String patientId = jsonData.getString("patientId");
        // 来源渠道
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }

        Patient pt = patientSwitchService.getPatientInfo(patientId);
        pt.setId(null);
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor(author);
        pt.setUserType(userType);
        pt.setSourceType(sourceType);
        pt.setTenantId(null);

        servParamMap.put("patient", pt);
        servParamMap.put("authorName", authorName);
        servParamMap.put("deptId", deptId);
        servParamMap.put("queueId", queueId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("authorId", author);
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", jsonData.getString("opNote"));
        servParamMap.put("opType", opType);
        //Edit by jiangq on 2023年08月23日 复制所有建档数据(配置问卷id一样的)
        final String srcTaskId = jsonData.getString("srcTaskId");
        HashMap<String,Object> paraMap  = new HashMap<>();
        paraMap.put("taskFlag", "1");
        paraMap.put("taskId", srcTaskId);
        if (!StringUtils.isEmpty(srcTaskId)) {
            List<PatientContentData> contentDataList = taskContentDAO.selectContentDataByTaskId(paraMap);
            Map<String, Object> quesMap = new HashMap<>();
            for (PatientContentData patientContentData : contentDataList) {
                quesMap.put(patientContentData.getQuestionId(), patientContentData.getQuestionAnswer());
            }
            servParamMap.put("contentData", quesMap);
        }else{
            servParamMap.put("contentData", jsonData.getJSONObject("questiones"));
        }
        Object outHospitalDay = jsonData.getJSONObject("outHospitalDay");
        String ohd = null;
        if (null == outHospitalDay)  {
            ohd = "2021-12-03";
        } else {
            ohd = outHospitalDay.toString();
            if (ohd.isEmpty())  {
                ohd = "2021-12-03";
            }
        }
        servParamMap.put("outHospitalDay", ohd);
        Map<String, Object> userMap = patientService.registerPatient(servParamMap);
        System.out.println(userMap.size());
        //Edit by jiangq on 2023年08月24日 随访数据复制，同一个窗口期内的日期对比复制
        List<PatientTask> patientTasks = patientTaskDao.selectById(paraMap);

        List<PatientContentData> addcontentDatas = new ArrayList<>();
        if(patientTasks.size() > 0){
            //老的随访任务
            String ptSchemeId = patientTasks.get(0).getPtSchemeid();
            paraMap.put("ptSchemeId", ptSchemeId);
            List<PatientTask> oldPatientTasks = patientTaskDao.selectByPtSchemeId(paraMap);
            //新的随访任务
            String newPptSchemeId = (String) userMap.get("ptSchemeId");
            paraMap.put("ptSchemeId", newPptSchemeId);
            List<PatientTask> newPatientTasks = patientTaskDao.selectByPtSchemeId(paraMap);
            String newTaskId = null;
            for (PatientTask newPatientTask : newPatientTasks) {
                if(newPatientTask.getSeqNo() == 0) continue;
                Date executeTime = DateUtil.getDate_8(newPatientTask.getExecuteTime());
                for (PatientTask task : oldPatientTasks) {
                    if(task.getSeqNo() == 0) continue;
                    if(DateUtil.getDate_8(task.getBeginTime()).getTime() <= executeTime.getTime() && DateUtil.getDate_8(task.getEndTime()).getTime() >= executeTime.getTime() && task.getSeqNo() != 0){
                        newTaskId = newPatientTask.getId();
                        HashMap<String,Object> mapIn  = new HashMap<>();
                        mapIn.put("taskId", task.getId());
                        List<PatientContentData> contentDataList = taskContentDAO.selectContentDataByTaskId(mapIn);
                        for (PatientContentData contentData : contentDataList) {
                            contentData.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
                            contentData.setTaskId(newTaskId);
                            contentData.setPtSchemeid(newPptSchemeId);
                            contentData.setQueueId(task.getQueueId());
                        }
                        addcontentDatas.addAll(contentDataList);
                    }
                }
            }
        }
        addcontentDatas = addcontentDatas.stream().filter(item -> !item.getQuestionAnswer().equals("") && item.getQuestionAnswer() != null).collect(Collectors.toList());
        if (!addcontentDatas.isEmpty()) {
            taskContentDAO.savePatientTaskContentDataBatch(addcontentDatas);
        }

        //复制原始建档任务中的出生体格数据到关联队列的建档任务中。
        Map<String,Object> targetDataMap= new HashMap<>();
        targetDataMap.put("tenantId", tenantId);
        targetDataMap.put("queueId",  queueId);
        targetDataMap.put("patientId",patientId );
        targetDataMap.put("ptSchemeId",  userMap.get("ptSchemeId"));
        if (!StringUtils.isEmpty(srcTaskId)) {
            Map<String,Object> retMap   = patientSwitchService.copyPatientFuData(srcTaskId, targetDataMap);
        } else {
            //由于没有原始随访任务，所以就无法复制了。
        }

        return new ResultModel(userMap);
    }


    /**
     * 查询可复制队列
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryQueue")
    @ResponseBody
    public ResultModel<Object> queryQueue(HttpServletRequest request,
                                                 @RequestBody String jsonStr) throws Exception {
        logger.warn("in queryQueue----arg==" + jsonStr);
        Map<String, Object> outMap = new HashMap<>();
        JSONObject json = JSON.parseObject(jsonStr);
        JSONObject jsonData = json.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        //获得病人id
        String patientId = jsonData.getString("patientId");
        //获得所有可加入的队列
        List<FollowQueue> queueList  = patientSwitchService.getQueueList(patientId);
        outMap.put("data",queueList);
        return new ResultModel<Object>(outMap);
    }


    /**
     * 查询建档信息
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryRecord")
    @ResponseBody
    public ResultModel<Object> queryRecord(HttpServletRequest request,
                                          @RequestBody String jsonStr) throws Exception {
        logger.warn("in queryRecord----arg==" + jsonStr);
        Map<String, Object> outMap = new HashMap<>();
        JSONObject json = JSON.parseObject(jsonStr);
        JSONObject jsonData = json.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        int groupType = (Integer) sessionMap.get("groupType");// 组织类型
        String rootGroupId = (String) sessionMap.get("rootGroupId");// 组织id
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String queueId = jsonData.getString("followQueueId");
        String userId = jsonData.getString("patientId");
        String ptSchemeId = jsonData.getString("ptSchemeId");
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("queueId", queueId);
        paramMap.put("seqNo", "0");
        paramMap.put("tenantId", tenantId);
        paramMap.put("groupType", groupType);
        String taskId = patientSwitchService.getPatientTask(paramMap);
        paramMap.put("taskId", taskId);
        HashMap<String, Object> retMap = patientService.qryPatientContentList(paramMap);
        return new ResultModel<Object>(retMap);
    }

    /**
     * 查询已经加入队列
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryPatient")
    @ResponseBody
    public ResultModel<Object> queryPatient(HttpServletRequest request,
                                          @RequestBody String jsonStr) throws Exception {
        logger.warn("in queryQueue----arg==" + jsonStr);

        List<PatientQueueInfo> list = new ArrayList<>();

        JSONObject json = JSON.parseObject(jsonStr);
        JSONObject jsonData = json.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> servParamMap = new HashMap<String, Object>();
        //获得病人姓名
        String patientName = jsonData.getString("patientName");
        if (StringUtils.isNotEmpty(patientName)) {
            servParamMap.put("userName", StrUtil.trim(patientName)+"%");
        }

        //获得病人手机号
        String phoneNo = jsonData.getString("phoneNo");
        if (StringUtils.isNotEmpty(phoneNo)) {
            servParamMap.put("phoneNo", phoneNo);
        }

        //获得所有符合要求人员
        List<Patient> patientList = patientService.getPatientList(servParamMap);

        Set<String> ids = new HashSet<>();
        //查看所有已经加入队列
        for (Patient patient: patientList) {
            if(ids.contains(patient.getId())){
               continue;
            }else{
                ids.add(patient.getId());
            }
            PatientQueueInfo patientQueueInfo =  new PatientQueueInfo();
            BeanUtils.copyProperties(patient, patientQueueInfo);
            String queueNames = patientSwitchService.getJoinQueueName(patient.getId());
            if(StringUtils.isNotEmpty(queueNames)){
                patientQueueInfo.setQueueName(queueNames);
                list.add(patientQueueInfo);
            }

        }

        return new ResultModel<Object>(list);
    }

    /**
     * 查询宝宝的详情。
     * @param jsonObj 母亲手机号、宝宝姓名。
     * @return
     */
    @RequestMapping(value = "queryBaby", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String,String>> queryBabyInfo(@RequestBody JSONObject jsonObj) {
        logger.info("++++queryBabyInfo() json param:"+jsonObj.toJSONString());
        final List<Map<String,String>> emptyList    = new ArrayList<>();
        final String key    = jsonObj.getString("key");
        if (StringUtils.isEmpty(key))   {
            return emptyList;
        }

        return patientSwitchService.queryBaby(key);
    }

    /**
     * 接收母乳分析结果。
     * @param jsonArg
     * @return
     */
    @RequestMapping(value = "putResult", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> putMilkResult(@RequestBody JSONObject jsonArg) {
        logger.info("++++putMilkResult() param jsonObj:"+jsonArg.toJSONString());
        final String hzguid = jsonArg.getString("hzguid");
        JSONObject dataObj = jsonArg.getJSONObject("data").getJSONObject("Body");

        Map<String,String> retMap   = new HashMap<>();
        String state    = "true";
        if (null==hzguid || hzguid.isEmpty())   {
            state   = "false";
            retMap.put("state", state);
            retMap.put("exception","未发送hzguid！");
        } else {
            //调用service查询pt_user_info是否存在该宝宝。
            final String id = patientSwitchService.backupMilkData(jsonArg);
            if (null == id) {
                logger.error("----putMilkResult() FAIL to backup breast milk data!");
            }
        }

        if (null==dataObj || dataObj.isEmpty())   {
            state   = "false";
            retMap.put("state", state);
            retMap.put("msg",   "接收母乳分析结果时发生错误！");
            retMap.put("exception","未发送data或data数据空！");
        }
        if (state.equalsIgnoreCase("true")) {
            //母乳分析结果参数正确。
            final String breastMilkType = dataObj.getString("Mrlx");

            final String fat    = dataObj.getString("Zf_nd");
            final String fatResult  = dataObj.getString("Zf_show");

            final String protein    = dataObj.getString("Dbz_nd");
            final String proteinResult  = dataObj.getString("Dbz_show");

            final String lactose    = dataObj.getString("Rt_nd");
            final String lactoseResult  = dataObj.getString("Rt_show");

            final String energy    = dataObj.getString("Nl_nd");
            final String energyResult  = dataObj.getString("Nl_show");

            final String mineral    = dataObj.getString("Kwz_nd");
            final String mineralResult  = dataObj.getString("Kwz_show");

            final String moisture   = dataObj.getString("Sf_nd");
            final String moistureResult = dataObj.getString("Sf_show");

            final String density    = dataObj.getString("Md2_nd");
            final String densityResult  = dataObj.getString("Md_show");

            final String jgfx   = dataObj.getString("Jgfx");    //结果分析。
            final String zdjy   = dataObj.getString("Zdjy");    //指导建议。
            logger.info("++++putMilkResult() data fat:"+fat+", fatResult:"+fatResult);

            Map<String,String> paraMap  = new HashMap<>();
            paraMap.put("userId",   hzguid);
            paraMap.put("fat",      fat);
            paraMap.put("protein",  protein);
            paraMap.put("lactose",  lactose);
            paraMap.put("energy",   energy);
            paraMap.put("mineral",  mineral);
            paraMap.put("moisture", moisture);
            paraMap.put("density",  density);
            paraMap.put("jgfx",  jgfx);
            paraMap.put("zdjy",  zdjy);
            paraMap.put("zcey_mrfx_mrlx",   breastMilkType);

            int updRet = patientSwitchService.updateMilkData(paraMap);
            if (1 == updRet) {
                retMap.put("state", "true");
                retMap.put("msg", "成功：接收了母乳分析结果数据。");
            } else {
                retMap.put("state", "false");
                retMap.put("msg", "失败：未接收母乳分析结果数据！");
            }
        }

        return retMap;
    }
/*
    public Map<String,String> putMilkResult(@RequestBody JSONObject jsonObj) {
        logger.info("++++putMilkResult() param jsonObj:"+jsonObj.toJSONString());

        final String hzguid = jsonObj.getString("hzguid");
        final JSONObject dataObj= jsonObj.getJSONObject("data");
        Map<String,String> retMap   = new HashMap<>();
        String state    = "true";
        if (null==hzguid || hzguid.isEmpty())   {
            state   = "false";
            retMap.put("state", state);
            retMap.put("exception","未发送hzguid！");
        } else {
            //调用service查询pt_user_info是否存在该宝宝。
            final String id = patientSwitchService.backupMilkData(jsonObj);
            if (null == id) {
                logger.error("----putMilkResult() FAIL to backup breast milk data!");
            }
        }

        if (null==dataObj || dataObj.isEmpty())   {
            state   = "false";
            retMap.put("state", state);
            retMap.put("msg",   "接收母乳分析结果时发生错误！");
            retMap.put("exception","未发送data或data数据空！");
        }
        if (state.equalsIgnoreCase("true")) {
            //母乳分析结果参数正确。
            final String breastMilkType = dataObj.getString("breastMilkType");

            final String fat    = dataObj.getString("fat");
            final String fatResult  = dataObj.getString("fatResult");

            final String protein    = dataObj.getString("protein");
            final String proteinResult  = dataObj.getString("proteinResult");

            final String lactose    = dataObj.getString("lactose");
            final String lactoseResult  = dataObj.getString("lactoseResult");

            final String energy    = dataObj.getString("energy");
            final String energyResult  = dataObj.getString("energyResult");

            final String mineral    = dataObj.getString("mineralSubstance");
            final String mineralResult  = dataObj.getString("mineralSubstanceResult");

            final String moisture   = dataObj.getString("breastMilkMoisture");
            final String moistureResult = dataObj.getString("breastMilkMoistureResult");

            final String density    = dataObj.getString("density");
            final String densityResult  = dataObj.getString("densityResult");
            logger.info("++++putMilkResult() data fat:"+fat+", fatResult:"+fatResult);

            Map<String,String> paraMap  = new HashMap<>();
            paraMap.put("userId",   hzguid);
            paraMap.put("fat",      fat);
            paraMap.put("protein",  protein);
            paraMap.put("lactose",  lactose);
            paraMap.put("energy",   energy);
            paraMap.put("mineral",  mineral);
            paraMap.put("moisture", moisture);
            paraMap.put("density",  density);
            paraMap.put("zcey_mrfx_mrlx",   breastMilkType);

            int updRet = patientSwitchService.updateMilkData(paraMap);
            if (1 == updRet) {
                retMap.put("state", "true");
                retMap.put("msg", "成功：接收了母乳分析结果数据。");
            } else {
                retMap.put("state", "false");
                retMap.put("msg", "失败：未接收母乳分析结果数据！");
            }
        }

        return retMap;
    }
*/

    /**
     * 合并、清洗重复建档的患者随访任务，包括患者的计划随访、临时随访和生长发育评估。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/mergePatient")
    @ResponseBody
    public ResultModel<Map<String, Object>> mergePatient(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++mergePatient() arg:" + arg.toString());
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String fromPatId  = jsonData.getString("fromId");
        final String toPatId    = jsonData.getString("toId");
        final String queueId    = jsonData.getString("queueId");
        if (StringUtils.isBlank(fromPatId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列fromId或值为空！"));
        }
        if (StringUtils.isBlank(toPatId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列toId或值为空！"));
        }
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列queueId或值为空！"));
        }

        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId     = sessionMap.get("tenantId").toString();
        final String doctorId     = sessionMap.get("authorId").toString();
        final String doctorName   = sessionMap.get("authorName").toString();
        Map<String,Object> retMap   = mergeService.merge(tenantId, doctorId, doctorName, fromPatId, toPatId, queueId);
        return new ResultModel(retMap);
    }

    /**
     * 查询重复患者质疑列表。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryDupList")
    @ResponseBody
    public ResultModel<List<Map<String, Object>>> queryDupPatList(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++queryDupPatList() arg:" + arg.toString());
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String queueId  = jsonData.getString("queueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列queueId或值为空！"));
        }

        Map<String,Object> paraMap  = new HashMap<>();
        final String pageNo = jsonData.getString("pageNo");
        if (StringUtils.isBlank(pageNo)) {
            paraMap.put("pageNo", 1);
        } else {
            paraMap.put("pageNo", Integer.valueOf(pageNo));
        }
        final String pageSize = jsonData.getString("pageSize");
        if (StringUtils.isBlank(pageSize)) {
            paraMap.put("pageSize", 5);
        } else {
            paraMap.put("pageSize", Integer.valueOf(pageSize));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId   = sessionMap.get("tenantId").toString();
        final List<Map<String,Object>> dupList    = mergeService.queryDupPatList(tenantId, queueId, paraMap);
        return new ResultModel(dupList);
    }

    /**
     * 查询已质疑列表。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryDuplicatedList")
    @ResponseBody
    public ResultModel<List<Map<String, Object>>> queryDuplicatedList(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++queryDuplicatedList() arg:" + arg.toString());
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String queueId  = jsonData.getString("queueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列queueId或值为空！"));
        }

        Map<String,Object> paraMap  = new HashMap<>();
        final String pageNo = jsonData.getString("pageNo");
        if (StringUtils.isNotBlank(pageNo)) {
            paraMap.put("pageNo", Integer.valueOf(pageNo));
        }
        final String pageSize = jsonData.getString("pageSize");
        if (StringUtils.isNotBlank(pageSize)) {
            paraMap.put("pageSize", Integer.valueOf(pageSize));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId   = sessionMap.get("tenantId").toString();
        final List<Map<String,Object>> duplicatedList   = mergeService.queryDuplicatedList(tenantId, queueId, paraMap);
        return new ResultModel(duplicatedList);
    }
}
